import React, { useEffect, useState } from 'react';
import { Table, Button, Upload, Pagination, message, Modal, Space } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { bindFileAndUser, fileListLength, returnFilesListData, updateDownload, deleteFile } from '@/api/file';
import dayjs from 'dayjs';

const FileManager = () => {
  const [tableData, setTableData] = useState([]);
  const [paginationData, setPaginationData] = useState({
    fileTotal: 1,
    filePageCount: 1,
    fileCurrentPage: 1,
  });


  useEffect(() => {
    getFileListLength();
    getFileFirstPageList();
  }, []);

  // 获取文件列表总数
  const getFileListLength = async () => {
    const res = await fileListLength();
    setPaginationData((prevData) => ({
      ...prevData,
      fileTotal: res.length,
      filePageCount: Math.ceil(res.length / 10),
    }));
  };

  // 获取文件列表第一页的数据
  const getFileFirstPageList = async () => {
    const data = await returnFilesListData(1);
    setTableData(data);
  };

  // 分页切换
  const fileCurrentChange = async (page) => {
    setPaginationData((prevData) => ({
      ...prevData,
      fileCurrentPage: page,
    }));
    const data = await returnFilesListData(page);
    setTableData(data);
  };

  // 文件上传成功回调
  const handleSuccess = (res) => {
    const name = JSON.parse(localStorage.getItem('userInfo')).name
    if (res.file.status === 'done') {
      bindFileAndUser(name, res.file.response.url).then(() => {
        message.success('上传文件成功');
        getFileFirstPageList();
        getFileListLength()
      });
    }
  };


  // 更新下载次数
  const changeClick = async (downloadNumber, id) => {
    await updateDownload(downloadNumber, id);
    setTimeout(() => {
      getFileFirstPageList();
      getFileListLength()
    }, 300);
  };

  // 删除文件
  const handleDeleteFile = (row) => {
    Modal.confirm({
      title: '提示',
      content: '确定删除该文件吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        const res = await deleteFile(row.id)
        if (res.status === 0) {
          message.success('删除成功');
          getFileFirstPageList()
        }
      }
    })
  };

  // 表格列定义
  const columns = [
    {
      title: '文件名',
      dataIndex: 'file_name',
    },
    {
      title: '文件大小',
      dataIndex: 'file_size',
      render: (text) => {
        return `${text?.slice(0, 2)}KB`;
      },
    },
    {
      title: '上传者',
      dataIndex: 'upload_person',
    },
    {
      title: '下载次数',
      dataIndex: 'download_number',
    },
    {
      title: '上传时间',
      dataIndex: 'upload_time',
      render: (text) => {
        return text ? dayjs(text).format('YYYY-MM-DD HH:mm:ss') : ''
      },
    },
    {
      title: '操作',
      key: 'operation',
      render: (_, row) => (
        <div>
          <Space>
            <a onClick={() => changeClick(row.download_number, row.id)}>
              <a href={row.file_url} target="_blank" rel="noopener noreferrer">
                下载文件
              </a>
            </a>
            <a style={{ color: 'red' }} onClick={() => handleDeleteFile(row)}>
              删除
            </a>
          </Space>
        </div>
      ),
    },
  ];

  return (
    <div className="table-wrapped">
      <div className="table-top">
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 20 }}>
          <div className="upload-wrapped">
            <Upload
              action="http://127.0.0.1:3007/file/uploadFile"
              multiple
              maxCount={3}
              onChange={handleSuccess}
              showUploadList={false}
            >
              <Button icon={<UploadOutlined />} type="primary">
                上传文件
              </Button>
            </Upload>
          </div>
        </div>
        <div className="table-content">
          <Table
            rowKey="id"
            columns={columns}
            dataSource={tableData}
            pagination={false}
            style={{ width: '100%' }}
          />
        </div>
      </div>
      <div style={{
        display: 'flex',
        justifyContent: 'flex-end',
        marginTop: 20,
      }}>
        <Pagination
          current={paginationData.fileCurrentPage}
          total={paginationData.fileTotal}
          pageSize={1}
          onChange={fileCurrentChange}
          showSizeChanger={false}
          showQuickJumper
          pageSizeOptions={['1']}
          showTotal={(total) => `共 ${total} 条`}
        />
      </div>
    </div>
  );
};

export default FileManager;
